package com.baoming.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.baoming.util.Struts2UploadUtil;

@SuppressWarnings("serial")
public class AjaxUploadServlet extends HttpServlet {
 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
  
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
		if (isMultipart) { 
			
			String allowType = "jpg,png,gif" ;
			
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter(); 
			int length = request.getContentLength()/1024;
			
			if(length > 1024){
				out.print("文件太大的了") ; 
				out.flush() ; 
				return ; 
			}
			
			MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request; 
			File[] file = wrapper.getFiles("pic") ;  
			String path = null ; 
			 
			
			if(file != null && file.length > 0 && file.length == 1){
				 
				String fileName = wrapper.getFileNames("pic")[0] ;  
				if(!allowType.contains(fileName.substring(fileName.lastIndexOf(".")+1))){ 
					
					out.print("不可上传文件的类型") ; 
					out.flush() ; 
					return ; 
				} 
				
				path = Struts2UploadUtil.uploadSimple(file[0],fileName , "upload") ;  
				response.setContentType("text/html");
				response.setCharacterEncoding("utf-8"); 
				out.print(path);
				out.flush() ; 
				return ; 
			} 
			
			out.print("上传失败");
			out.flush() ; 
			
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
